import modelExtend from "dva-model-extend";
import { pageModel } from "./common";
import { routerTool, config } from "utils";
import { departmentService } from "services";

export default modelExtend(pageModel, {
  namespace: 'departments',

  state: {},

  subscriptions: {
    setup ({ dispatch, history }) {
      dispatch({ type: "loadDepartments" });
      return history.listen(location => {
        if (location.pathname === routerTool.getPathByName("OrganizationMember")) {
          dispatch({ type: "loadDepartments" });
        }
      });
    },
  },

  reducers: {
    updateList (state, { payload }) {
      const { depts } = payload;
      return {
        ...state,
        ...{
          list: depts,
        },
      };
    },
  },

  effects: {
    *loadDepartments (_, { put, call, select }) {
      // 获取当前组织
      const { organization } = yield select(_ => _.user);
      const { success, results } = yield call(departmentService.queryAllDept, {
        org: organization.ID,
      });

      if (success) {
        const { Departments } = results;

        // 更新部门
        yield put({
          type: 'updateList',
          payload: {
            depts: Departments,
          },
        });
        // const { currentDept } = yield select(_ => _.organizationDepartment);
      }
    },

    
  },

});
